package com.ruoyi.app.framework.resolver;

import com.ruoyi.common.annotation.AuthMember;
import com.ruoyi.common.entity.DO.member.MemberDO;
import lombok.NoArgsConstructor;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * 用于绑定@AuthMember的方法参数解析器
 *
 * @author lijiantao
 */
@NoArgsConstructor
public class AuthMemberMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(MemberDO.class) && parameter.hasParameterAnnotation(AuthMember.class);
    }

    @Override
    public MemberDO resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        MemberDO member = new MemberDO();
        Object memberIdStr = request.getAttribute("memberId");
        Object shopIdStr = request.getAttribute("shopId");
        Object openid = request.getAttribute("openid");
        if (memberIdStr != null && shopIdStr != null && openid != null) {
            member.setId(Long.valueOf(memberIdStr.toString()));
            member.setShopId(Long.valueOf(shopIdStr.toString()));
            member.setOpenid(openid.toString());
        }
        return member;
    }
}